package com.speech.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog;
import com.speech.AppConfig;
import com.speech.MyApplication;
import com.speech.R;
import com.speech.constant.PrefsConstant;
import com.speech.db.SharedPreferenceHelper;
import com.speech.entity.BaseEntity;
import com.speech.entity.LoginInfo;
import com.speech.http.BaseCallback;
import com.speech.net.BasicCallBack;
//import com.speech.net.HttpCommunicationManager;
import com.speech.net.constant.EnumDeviceType;
import com.speech.net.constant.EnumReqestActionCode;
import com.speech.net.entity.MessageC2S;
import com.speech.net.entity.MessageC2SBuilder;
import com.speech.net.entity.MessageS2C;
import com.speech.net.request.UserLogin_Request;
import com.speech.net.result.UpdateInfo_Result;
import com.speech.net.result.UserAuth_Result;
import com.speech.result.Result;
import com.speech.utils.ApkVersionUtil;
import com.speech.utils.DeviceUtil;
import com.speech.utils.JsonProcessor;

import me.leolin.shortcutbadger.ShortcutBadger;
import retrofit2.Call;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private EditText edt_account;
    private EditText edt_password;

    private ImageView img_visible;

    private Button btn_login;

    private TextView tv_forget;
    private TextView tv_register;

    private boolean bPasswordVisible = false;
    private SweetAlertDialog dialog;
    private SweetAlertDialog dialog1;
    private SweetAlertDialog dialog2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        _initView();

//        int badgeCount = 1;

//        ShortcutBadger.applyNotification();

//        ShortcutBadger.removeCount(this); //for 1.1.4+

        //TODO:临时的升级检查
        _temp_check_version_change();


        img_visible.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bPasswordVisible) {
                    //设置密码不可见
                    img_visible.setImageResource(R.drawable.eyes_close);
                    edt_password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);

                } else {
                    //设置密码可见
                    img_visible.setImageResource(R.drawable.eyes_open);
                    edt_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

                }
                bPasswordVisible = !bPasswordVisible;
            }
        });

        edt_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (edt_password != null && edt_password.getText().toString().length() > 0
                        && edt_account != null && edt_account.getText().toString().length() > 0) {
                    btn_login.setTextColor(Color.WHITE);
                    btn_login.setClickable(true);
                } else {
                    btn_login.setTextColor(getResources().getColor(R.color.colorGray_DefaultState));
                    btn_login.setClickable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        // 登录
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog = new SweetAlertDialog(LoginActivity.this,SweetAlertDialog.PROGRESS_TYPE);
                dialog.setTitleText("Loading");
                dialog.setCancelable(false);
                dialog.show();

                UserLogin_Request login_request = new UserLogin_Request();
                login_request.strDeviceId = DeviceUtil.getDeviceID(LoginActivity.this);
                login_request.strPassword = edt_password.getText().toString();
                login_request.phone = Long.valueOf(edt_account.getText().toString());
                login_request.deviceType = EnumDeviceType.ANDROID;


                //TODO: 接口请求
//                MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(LoginActivity.this, EnumReqestActionCode.登录, JsonProcessor.StcGetJson(login_request));
//
//                String json = JsonProcessor.StcGetJson(msg_c2s);
//
//                HttpCommunicationManager.getInstance().doPost(json,new BasicCallBack(LoginActivity.this, json, new BasicCallBack.BasicCallBackListener() {
//                    @Override
//                    public void success(MessageS2C msg_s2c) {
//                        Log.d(AppConfig.LOG_TAG,"登陆成功");
//                        SharedPreferenceHelper spf_helper = new SharedPreferenceHelper(LoginActivity.this, PrefsConstant.FILE_USER_INFO);
//                        spf_helper.putData(PrefsConstant.KEY_USER_INFO_INT_LOGIN_STATE,1);
//                        UserAuth_Result rst = JsonProcessor.StcGetObject(UserAuth_Result.class,msg_s2c.strData);
//                        spf_helper.putData(PrefsConstant.KEY_USER_INFO_LONG_UID,rst.uid);
//                        spf_helper.putData(PrefsConstant.KEY_USER_INFO_LONG_TOKEN,rst.token);
//
//                        dialog.dismiss();
//                        startActivity(new Intent(LoginActivity.this,HomeActivity.class));
//                        finish();
//                    }
//
//                    @Override
//                    public void fail(MessageS2C msg_s2c) {
//                        dialog.dismiss();
//                        new SweetAlertDialog(LoginActivity.this,SweetAlertDialog.ERROR_TYPE)
//                                .setTitleText(msg_s2c.strMsgUI)
//                                .setConfirmText("OK")
//                                .show();
//                    }
//
//                })

                Log.e("deviceId==",DeviceUtil.getDeviceID(LoginActivity.this));
                Call<Result<LoginInfo>> call = MyApplication.getInstance().getApiService()
                        .login(edt_account.getText().toString(),edt_password.getText().toString()
                                ,DeviceUtil.getDeviceID(LoginActivity.this));
                call.enqueue(new BaseCallback<LoginInfo>() {
                    @Override
                    public void onSuccess(LoginInfo baseEntity) {
                        SharedPreferenceHelper spf_helper = new SharedPreferenceHelper(LoginActivity.this, PrefsConstant.FILE_USER_INFO);
                        spf_helper.putData(PrefsConstant.KEY_USER_INFO_INT_LOGIN_STATE,1);
//                        UserAuth_Result rst = JsonProcessor.StcGetObject(UserAuth_Result.class,baseEntity.getContent());
                        spf_helper.putData(PrefsConstant.KEY_USER_INFO_LONG_UID,baseEntity.getUid());
                        spf_helper.putData(PrefsConstant.KEY_USER_INFO_LONG_TOKEN,baseEntity.getToken());

                        dialog.dismiss();
                        startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                        finish();
                    }

                    @Override
                    public void onAbnormal(String msg) {
                        dialog.dismiss();

                    }

                    @Override
                    public void onFailure(String msg) {
                        dialog.dismiss();
                        dialog1 = new SweetAlertDialog(LoginActivity.this,SweetAlertDialog.ERROR_TYPE)
                                .setTitleText(msg)
                                .setConfirmText("OK");
                                dialog1.show();

                    }
                });


            }
        });

        tv_forget.setOnClickListener(this);
        tv_register.setOnClickListener(this);
    }

    private void _initView() {
        edt_account = findViewById(R.id.edt_login_account);
        edt_password = findViewById(R.id.edt_login_password);

        img_visible = findViewById(R.id.img_login_eyes);

        btn_login = findViewById(R.id.btn_login_submit);

        tv_forget = findViewById(R.id.tv_login_forget);

        tv_register = findViewById(R.id.tv_login_register);

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        if (v == tv_forget) {
            intent = new Intent(LoginActivity.this,FindPasswordStep1Activity.class);
        } else if (v == tv_register) {
            intent = new Intent(LoginActivity.this, RegisterActivity.class);
        }

        if (intent != null) {
            startActivity(intent);
            finish();
        }
    }

    private void _temp_check_version_change() {

        //TODO: 接口请求
//        MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(this, EnumReqestActionCode.查询更新, null);
//        String json = JsonProcessor.StcGetJson(msg_c2s);
//        HttpCommunicationManager.getInstance().doPost(json, new BasicCallBack(LoginActivity.this, json, new BasicCallBack.BasicCallBackListener() {
//            @Override
//            public void success(MessageS2C msg_s2c) {
//                UpdateInfo_Result updateInfo_result = JsonProcessor.StcGetObject(UpdateInfo_Result.class, msg_s2c.strData);
//
//                if (updateInfo_result != null && _check_need_update(updateInfo_result)) {
//                    SweetAlertDialog dialog = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.WARNING_TYPE)
//                            .setTitleText("新版本上线啦")
//                            .setContentText("请进入公众号内下载最新版本")
//                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                                @Override
//                                public void onClick(SweetAlertDialog sweetAlertDialog) {
//                                    sweetAlertDialog.dismiss();
//                                    MyApplication.getInstance().destory();
//                                    LoginActivity.this.finish();
//                                }
//                            });
//                    dialog.setCancelable(false);
//                    dialog.show();
//                }
//
//            }
//
//            @Override
//            public void fail(MessageS2C msg_s2c) {
//
//            }
//        }));

        String uid,token;
        SharedPreferenceHelper spf = new SharedPreferenceHelper(this, PrefsConstant.FILE_USER_INFO);
        String lUID = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_UID, "");
        uid = lUID;
        String lToken = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_TOKEN, "");
        token = lToken;
        Call<Result<BaseEntity>> call = MyApplication.getInstance().getApiService()
                .upApp(uid,DeviceUtil.getDeviceID(this)
                        ,token,ApkVersionUtil.getVersionName(this));
        call.enqueue(new BaseCallback<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity baseEntity) {
//                dialog2 = new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText("新版本上线啦")
//                        .setContentText("请进入公众号内下载最新版本")
//                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                            @Override
//                            public void onClick(SweetAlertDialog sweetAlertDialog) {
//                                sweetAlertDialog.dismissWithAnimation();
//                                MyApplication.getInstance().destory();
//                                LoginActivity.this.finish();
//                            }
//                        });
//                dialog2.setCancelable(false);
//                dialog2.show();
            }

            @Override
            public void onAbnormal(String msg) {

            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    private boolean _check_need_update(UpdateInfo_Result updateInfo_result) {

        String[] strServerVersion = updateInfo_result.strEnforcementUpdateVersion.split("\\.");
        String[] strCurrentVersion = ApkVersionUtil.getVersionName(LoginActivity.this).split("\\.");
        boolean bNeedUpdate = false;

        for (int index = 0; index < strServerVersion.length; index++) {
            int iServerVerison = Integer.valueOf(strServerVersion[index]);
            int iCurrentVersion = Integer.valueOf(strCurrentVersion[index]);
            if (iServerVerison > iCurrentVersion) {
                bNeedUpdate = true;
                break;
            }
        }

        return bNeedUpdate;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null){
            dialog.dismissWithAnimation();
        }
        if (dialog1 != null){
            dialog1.dismissWithAnimation();
        }
        if (dialog2 != null){
            dialog2.dismissWithAnimation();
        }
    }
}
